package com.mymall.serve.service;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 类
 *
 * @author weiwei
 * @since 2020-06-02 10:10
 **/
@Slf4j
public class ThreadTest {
    public static int f1(){
        log.info("f1线程开始");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("f1线程结束");
        return 1;
    }

    public static int f2(){
        log.info("f2线程开始");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("f2线程结束");
        return 2;
    }

    public static int f3(){
        log.info("f3线程开始");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("f3线程结束");
        return 2;
    }

    public static void main(String[] args) {
        int a ;
        int b ;
        int c ;
        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> {
            return f2();
        });
        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {
            return f1();
        });
        CompletableFuture<Integer> cf3 = CompletableFuture.supplyAsync(() -> {
            return f3();
        });

        CompletableFuture<Void> allFu = CompletableFuture.allOf(cf1,cf2,cf3);
        long l1 = System.currentTimeMillis();
        log.info("开始阻塞");
        try {
            allFu.get(3, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            System.out.println("超时了");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("其他");
            e.printStackTrace();
        }
        long l2 = System.currentTimeMillis();
        log.info("阻塞结束"+String.valueOf(l2-l1));
        a = cf1.getNow(0);
        b = cf2.getNow(0);
        c = cf3.getNow(0);
        long l3 = System.currentTimeMillis();
        log.info("阻塞结束2"+String.valueOf(l3-l2));
        System.out.println(a + "-" + b + "-" + c);
    }
}
